package com.creatified.jacqueline;

import java.util.ArrayList;
import org.apache.log4j.Logger;

/**
 * A JacquelineResult is basically a list of JacquelineSelector objects.
 * It also features some methods which allow you to find all matching or all non-matching etc. JacquelineSelectors
 */

@SuppressWarnings("serial")
public class JacquelineResult extends ArrayList<JacquelineSelector> {
	
	protected static Logger LOG = Logger.getLogger(JacquelineResult.class);

	public JacquelineResult() {
		super();
	}

	/**
	 * Gets all matching JacquelineSelector instances
	 * 
	 * @return the matching selectors
	 */
	public JacquelineResult getMatchingSelectors() {
		return getSelectors(1, Integer.MAX_VALUE);
	}
	
	/**
	 * Gets all not matching JacquelineSelector instances
	 * 
	 * @return the not matching selectors
	 */
	public JacquelineResult getNonMatchingSelectors() {
		return getSelectors(0, 0);
	}
	
	/**
	 * Gets all selectors
	 * 
	 * @return the selectors
	 */
	public JacquelineResult getSelectors() {
		return this;
	}
	
	/**
	 * Gets all selectors matching the given min/max criteria
	 * 
	 * @param minMatches the minimum amout of matches (inclusive)
	 * @param maxMatches the maximum amout of matches (inclusive)
	 * 
	 * @return all matching selectors
	 */
	public JacquelineResult getSelectors(int minMatches, int maxMatches) {
		JacquelineResult result = new JacquelineResult();
		
		for(JacquelineSelector selector: this) {
			if(selector.getTimesUsed() > 1) {
				LOG.info("Selector: " + selector.getSelectorText() + " used " + selector.getTimesUsed() + " time(s)");
			}
			if(selector.getTimesUsed() >= minMatches && selector.getTimesUsed() <= maxMatches) {
				result.add(selector);
			}
		}

		return result;
	}
	
	/**
	 * Utility method to merge two JacquelineResults into one.
	 * 
	 * @param a the first JacquelineResult
	 * @param b the second JacquelineResult
	 * 
	 * @return the merged JacquelineResult
	 */
	protected static JacquelineResult mergeResults(JacquelineResult a, JacquelineResult b) {
		
		JacquelineResult result = a;
		
		if(result == null || result.isEmpty()) {
			return b;
		}
		
		for(JacquelineSelector sel: b.getSelectors()) {
			if(result.contains(sel)) {
				JacquelineSelector buffer = result.get(result.indexOf(sel));
				
				int newValue = buffer.getTimesUsed() + sel.getTimesUsed();
				
				buffer.setTimesUsed(newValue);
			} else {
				result.add(sel);
			}
		}
		
		return result;
	}
	
}
